<template>
  <div class="carousel-upload">
    <div class="upload-grid">
      <div v-for="(item, index) in carouselItems" :key="index" class="upload-item">
        <el-upload
          class="uploader"
          :action="`/api/admins/upload`"
          :headers="uploadHeaders"
          :show-file-list="false"
          :before-upload="(file) => beforeUpload(file, index)"
          :on-success="(response) => handleSuccess(response, index)"
          :on-error="handleError"
          name="file"
          :data="{ bannerId: item.id }"
          accept="image/*"
        >
          <template v-if="item.url">
            <div class="image-container">
              <img :src="item.url" class="uploaded-image" />
              <div class="image-overlay">
                <el-button
                  type="danger"
                  circle
                  class="delete-btn"
                  @click.stop="handleRemove(item)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
          </template>
          <div v-else class="upload-placeholder" >
            <span>点击上传</span>
          </div>
        </el-upload>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getBannersList, clearBanner } from '@/api/topic'
import { useTokenStore } from '@/stores/token.js'
import { Delete } from '@element-plus/icons-vue'

const tokenStore = useTokenStore()

const uploadHeaders = computed(() => ({
  'Authorization': tokenStore.token,
  'Accept': 'application/json'
}))

const carouselItems = ref(Array(6).fill().map((_, index) => ({ 
  id: index + 1,
  url: '', 
  order: index + 1
})))

// 上传前的验证
const beforeUpload = (file, index) => {
  console.log('开始上传文件:', file)
  console.log('文件类型:', file.type)
  console.log('文件大小:', file.size)
  console.log('当前位置索引:', index)

  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB！')
    return false
  }
  return true
}

// 获取已有的轮播图列表
const fetchBanners = async () => {
  try {
    const response = await getBannersList()
    if (response.data) {
      // 确保只显示前6条数据
      const banners = response.data.slice(0, 6)
      // 用现有数据填充数组
      carouselItems.value = Array(6).fill().map((_, index) => {
        if (index < banners.length) {
          return {
            id: banners[index].bid || index + 1,
            url: banners[index].imageUrl || '',
            order: banners[index].order || index + 1
          }
        }
        return {
          id: index + 1,
          url: '',
          order: index + 1
        }
      })
    }
  } catch (error) {
    console.error('获取轮播图列表失败：', error)
    ElMessage.error('获取轮播图列表失败')
  }
}

// 上传成功的回调
const handleSuccess = (response, index) => {
  console.log('上传响应:', response)
  if (response.code === 200 && response.data && response.data.length > 0) {
    carouselItems.value[index].url = response.data
    ElMessage.success('上传成功')
    fetchBanners() // 刷新列表
  } else {
    console.error('上传失败响应:', response)
    if (response.code === 200 && (!response.data || response.data.length === 0)) {
      ElMessage.error('上传失败：服务器未返回文件URL')
    } else {
      ElMessage.error(response.msg || '上传失败')
    }
  }
}

// 上传失败的回调
const handleError = (error) => {
  console.error('上传错误详情：', error)
  if (error.response) {
    console.error('错误响应数据：', error.response)
    ElMessage.error(`上传失败：${error.response.data?.msg || error.message || '未知错误'}`)
  } else if (error.request) {
    ElMessage.error('上传失败：服务器无响应')
  } else {
    ElMessage.error('上传失败：' + (error.message || '未知错误'))
  }
}

// 处理图片清除
const handleRemove = async (item, index) => {
  try {
    await ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    if (item.url) {
      console.log('清除图片，ID: ' + item.id);
      await clearBanner(item.id);
      // 清空URL但保留其他信息
      carouselItems.value[index] = {
        ...item,
        url: ''
      }
      ElMessage.success('删除成功')
      fetchBanners() // 刷新列表
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败：', error)
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  }
}
onMounted(() => {
  fetchBanners()
})
</script>

<style scoped>
@import '@/assets/css/topic/upload.css';

.image-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100px;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

.delete-btn {
  z-index: 10;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>